package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;

import com.itheima.entity.Result;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.Power_UserService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/power")
public class PowerController {

    @Reference
    private Power_UserService power_userService;

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return power_userService.findPage(queryPageBean);
    }

    //新增用户
    @RequestMapping("/add")
    public Result add(@RequestBody User user){
        try {
            power_userService.add(user);
            return new Result(true, MessageConstant.ADD_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_USER_FAIL);
        }
    }

    //查询角色表单 回显
    @RequestMapping("/findRole")
    public Result findRole(){
        try {
            List<Role> list = power_userService.findRole();
            return new Result(true,MessageConstant.QUERY_USER_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_USER_FAIL);
        }
    }

    //根据用户id查询其关联角色
    @RequestMapping("/findrolesByUserId")
    public Result  findrolesByUserId(Integer userId){
        try {
            List<Integer> list = power_userService.findrolesByUserId(userId);
            return new Result(true,MessageConstant.QUERY_USER_ROLE_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_USER_ROLE_FAIL);
        }
    }

    //添加角色或者修改关联角色
    @RequestMapping("/edit")
    public Result edit(Integer[] roles,Integer userId){
        try {
            power_userService.edit(roles,userId);
            return new Result(true,MessageConstant.ADD_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_USER_FAIL);
        }
    }

    //删除用户
    @RequestMapping("/delete")
    public Result delete(Integer userId){
        try {
            power_userService.delete(userId);
            return new Result(true,MessageConstant.DELETE_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_USER_FAIL);
        }
    }
}
